package components.utils
{
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	import flash.utils.clearInterval;
	import flash.utils.clearTimeout;
	import flash.utils.setInterval;
	import flash.utils.setTimeout;

	public class TimeoutIntervalUtil
	{
		//key:displayObject,value:list
		private static var _timeoutDisplayObjectDic:Dictionary=new Dictionary();

		//key:displayObject,value:list
		private static var _setIntervalDisplayObjectDic:Dictionary=new Dictionary();

		public static function addSetTimeout(object:Object, closure:Function, delay:Number, ... parameters):uint
		{
			if (_timeoutDisplayObjectDic[object] == null)
				_timeoutDisplayObjectDic[object]=[];

			parameters.unshift(closure, delay);

			var id:int=setTimeout.apply(null, parameters);

			_timeoutDisplayObjectDic[object].push(id);
			return id;

		}

		public static function addSetInterval(object:Object, closure:Function, delay:Number, ... parameters):uint
		{
			if (_setIntervalDisplayObjectDic[object] == null)
				_setIntervalDisplayObjectDic[object]=[];

			parameters.unshift(closure, delay);

			var id:int=setInterval.apply(null, parameters);

			_setIntervalDisplayObjectDic[object].push(id);
			return id;
		}

		public static function removeObject(object:Object):void
		{
			var list:Array;
			var i:int;

			if (_timeoutDisplayObjectDic[object])
			{
				list=_timeoutDisplayObjectDic[object];

				while (list.length > 0)
				{
					clearTimeout(list.pop());
				}

				delete _timeoutDisplayObjectDic[object];
			}

			if (_setIntervalDisplayObjectDic[object])
			{
				list=_setIntervalDisplayObjectDic[object];

				while (list.length > 0)
				{
					clearInterval(list.pop());
				}

				delete _setIntervalDisplayObjectDic[object];
			}
		}
	}
}